package com.sort;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-13
 * Time: 10:03
 */
public class InsertSort {
    public static void insertSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int insertVal = arr[i];
            int index = i - 1;
            //从小到大，大的不断向后
            while (index >= 0 && insertVal < arr[index]) {
                arr[index + 1] = arr[index];
                index--;
            }
            //出来时index的位置是最后交换的前一个，所以要+1
            arr[index + 1] = insertVal;
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 5, 7, 5, 1};
        insertSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
